import React, { useEffect, useRef } from 'react';
import '@jd/just-map/dist/index.css';
import { JustMap } from '@jd/just-map';

export default ({ id, loadDone, loadError, baseUrl, jServer, styleType = 'justmap', mapOptions, isUpdate }) => {
  const mapContainerRef = useRef();
  const mapRef = useRef();
  const justBox = `just_box_${id}`;
  useEffect(() => {
    mapRef.current = new JustMap({
      styleType,
      style: jServer,
      baseUrl,
      mapboxOptions: {
        minZoom: 3,
        ...mapOptions,
        container: mapContainerRef.current,
      },
    });
    mapRef.current.on('load', () => {
      if (isUpdate) {
        mapRef.current.resize();
      }
      if (!window.$$just) {
        window.$$justMap = {};
      }
      window.$$justMap[justBox] = mapRef.current;
      loadDone && loadDone(mapRef.current);
      // eslint-disable-next-line
      console.log(
        '%c JUST-MAP %c 初始化完成 %c',
        'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
        'background:#41b883 ; padding: 1px; border-radius: 0 3px 3px 0;  color: #fff',
        'background:transparent'
      );
    });
    mapRef.current.on('error', (e) => {
      loadError && loadError(e);
    });
  }, []);

  return (
    <div id={justBox} style={{ width: '100%', height: '100%', margin: 0, padding: 0, position: 'relative' }}>
      <div id={`other_contener_${id}`} style={{ width: '100%', height: '100%', position: 'absolute', top: 0, left: 0, zIndex: 1 }}></div>
      <div ref={mapContainerRef} style={{ width: '100%', height: '100%', position: 'absolute', top: 0, left: 0, zIndex: 3, opacity: 1 }}></div>
    </div>
  );
};
